const path = require("path");
const fs = require("fs");
const PageConfig = require('./page-config');

const EXTENSIONS = {
	".html": "text/html",
	".css": "text/css",
	".js": "application/javascript",
	".png": "image/png",
	".gif": "image/gif",
	".jpg": "image/jpeg"
};

function getFile(localPath) {
	console.log(`localPath: ${localPath}`);
	return new Promise((resolve, reject) => {
		// verify that this file actually exists and load it, or else return a 404
		fs.exists(localPath, function (exists) {
			if (exists) {
				// read the file in and return it, or return a 500 if it can't be read
				fs.readFile(localPath, function (err, content) {
					if (!err) {
						resolve(content);
					}
					else {
						reject();
					}
				});
			}
			else {
				reject();
			}
		});
	});
}

const readFile = (pathname = PageConfig.INDEX) => {
	return new Promise((resolve, reject) => {
		const ext = path.extname(pathname)

		if (EXTENSIONS[ext]) {
			// verify that this file actually exists and load it, or else return a 404
			getFile(pathname).then(content=>{
				resolve({
					content,
					contentType: EXTENSIONS[ext],
				});
			}).catch(err=>{
				console.error(err);
			});
		}
		else{
			reject();
		}
	}).catch(err=>{
		console.error(err);
	});
}

exports.readFile = readFile;